package xyz.luhui1hao.sell.service.impl;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import xyz.luhui1hao.sell.converter.OrderMaster2OrderDTOConverter;
import xyz.luhui1hao.sell.domain.OrderDetail;
import xyz.luhui1hao.sell.domain.OrderMaster;
import xyz.luhui1hao.sell.domain.ProductInfo;
import xyz.luhui1hao.sell.dto.CartItemDTO;
import xyz.luhui1hao.sell.dto.OrderDTO;
import xyz.luhui1hao.sell.enums.OrderStatusEnum;
import xyz.luhui1hao.sell.enums.PayStatusEnum;
import xyz.luhui1hao.sell.enums.ResultEnum;
import xyz.luhui1hao.sell.exception.SellException;
import xyz.luhui1hao.sell.mapper.OrderDetailMapper;
import xyz.luhui1hao.sell.mapper.OrderMasterMapper;
import xyz.luhui1hao.sell.service.OrderService;
import xyz.luhui1hao.sell.service.PayService;
import xyz.luhui1hao.sell.service.ProductInfoService;
import xyz.luhui1hao.sell.utils.KeyUtil;
import xyz.luhui1hao.sell.utils.NumberArithmeticUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import static xyz.luhui1hao.sell.converter.OrderDetail2CartItemDTOConverter.convert;

/**
 * @ClassName OrderServiceImpl
 * @Description TODO
 * @Author luhui1hao
 * @Date 2018/8/22 上午11:05
 * @Version 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMasterMapper orderMasterMapper;
    @Autowired
    private PayService payService;

    @Override
    @Transactional
    public OrderDTO createOrder(OrderDTO orderDTO) {
        String orderId = KeyUtil.genUniqueKey();//主键
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);//总价
        List<CartItemDTO> cartItemDTOList;//购物车列表

        //1.查询商品（数量，价格）
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            //2.计算订单总价
            BigDecimal detailAmount = NumberArithmeticUtils.safeMultiply(productInfo.getProductPrice()
                    , orderDetail.getProductQuantity());
            orderAmount = NumberArithmeticUtils.safeAdd(detailAmount, orderAmount);

            //3.订单详情入库
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetailMapper.insertOrderDetail(orderDetail);
        }

        //4.订单详情入库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        BeanUtils.copyProperties(orderDTO, orderMaster, new String[]{"orderStatus", "payStatus", "orderAmount"});
        orderMasterMapper.insertOrderMaster(orderMaster);

        //5.扣库存
        cartItemDTOList = convert(orderDTO.getOrderDetailList());
        productInfoService.decreaseStock(cartItemDTOList);

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterMapper.findByOrderId(orderId);
        if (orderMaster == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    @Override
    public List<OrderDTO> findList(String buyerOpenId, int page, int size) {
        PageHelper.startPage(page, size);
        List<OrderMaster> orderMasterList = orderMasterMapper.findByBuyerOpenId(buyerOpenId);
        if (CollectionUtils.isEmpty(orderMasterList)) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterList);

//        for (OrderDTO orderDTO : orderDTOList) {
//            List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(orderDTO.getOrderId());
//            if (CollectionUtils.isEmpty(orderDetailList)) {
//                throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
//            }
//
//            orderDTO.setOrderDetailList(orderDetailList);
//        }

        return orderDTOList;
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确，orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        int updateResult = orderMasterMapper.updateOrderMaster(orderMaster);
        if (updateResult == 0) {
            log.error("【取消订单】更新失败，orderMaster = {}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        //返还库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情，orderDTO = {}", orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        productInfoService.increaseStock(convert(orderDTO.getOrderDetailList()));
        //如果已支付，需要退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            payService.refund(orderDTO);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO finish(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【完结订单】订单状态不正确，orderId = {}, orderStatus = {}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        OrderMaster orderMaster = orderMasterMapper.findByOrderId(orderDTO.getOrderId());
        orderDTO.setOrderStatus(OrderStatusEnum.FINISH.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);

        int result = orderMasterMapper.updateOrderMaster(orderMaster);
        if (result == 0) {
            log.error("【完结订单】更新失败，orderMaster = {}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO pay(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【支付订单】订单状态不正确，orderId = {}, orderStatus = {}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("【支付订单】支付状态不正确，orderId = {}, payStatus = {}", orderDTO.getOrderId(), orderDTO.getPayStatus());
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }
        //修改支付状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        int result = orderMasterMapper.updateOrderMaster(orderMaster);
        if (result == 0) {
            log.error("【支付订单】支付失败，orderId = {}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        return orderDTO;
    }
}
